from django.shortcuts import render, redirect
from .. import models
from ..utils.pagination import Pagination
from ..forms import UserMyForm

def user_list(request):
    """用户管理"""
    # 获取所用用户列表
    queryset = models.EmployInfo.objects.all()
    # for i in queryset:  # python 语法
    # type(i.create_time)为datatime
    # i.gender  # 1/2
    # i.get_gender_display()  # get_字段名称_display()
    # i.depart # 根据id自动去关联的表中获取哪一行数据depart对象。
    # print(i.id, i.name, i.account, i.create_time.strftime("%Y-%m-%d"), i.gender, i.get_gender_display(), i.depart_id, i.depart.title)

    page_object = Pagination(request, queryset, page_size=2)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, "app_02/user_list.html", context)


def user_add(request):
    """添加部门(ModelForm版本)"""
    if request.method == "GET":
        form = UserMyForm()
        return render(request, "app_02/user_add.html", {"form": form})

    # 用户POST提交过来的数据, 数据校验(创建)
    form = UserMyForm(data=request.POST)
    # form.is_valid()拿到的数据逐一效验
    if form.is_valid():
        # 如果数据合法, 保存到数据库
        # {'name': '3rfaf', 'password': 'fasfd', 'age': 22, 'account': Decimal('143124'),'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Shanghai')),'gender': 1, 'depart': < Department: IT部门 >}
        # print(form.cleaned_data)
        form.save()
        # 重定向回部门列表
        return redirect("/app_02/user/list")
    # 校验失败
    return render(request, "app_02/user_add.html", {"form": form})


def user_edit(request, nid):
    """编辑用户"""
    # 根据ID去数据库获取要编辑的那一行数据(对象)或者获取post请求的数据
    row_object = models.EmployInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        # 显示之前数据(不会校验)
        form = UserMyForm(instance=row_object)
        return render(request, "app_02/user_edit.html", {"form": form, "row_object": row_object})

    # 验证
    form = UserMyForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据
        form.save()
        return redirect("/app_02/user/list/")
    return render(request, "app_02/user_edit.html", {"form": form, "row_object": row_object})


def user_delete(request, nid):
    models.EmployInfo.objects.filter(id=nid).delete()
    return redirect("/app_02/user/list/")